package com.huaxin.common;

import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.LayoutRes;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestOptions;
import com.huaxin.common.cache.ACache;
import com.huaxin.common.tools.RequestHelper;
import com.huaxin.common.utils.StringUtils;
import com.huaxin.common.utils.Util;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import butterknife.ButterKnife;
import butterknife.Unbinder;
import retrofit2.Call;

/**
 * Created by hebing on 2016/3/30.
 * 抽象的activity基类
 * ID相同时会被替换为主应用中的
 */
public abstract class BaseActivity extends AppCompatActivity {

    /**
     * Three status of activity before show
     */
    protected static final int LOADING      = 0x0101;//加载界面
    protected static final int LOAD_ERROR   = LOADING + 1;//加载错误
    protected static final int LOAD_SUCCESS = LOADING + 2;//加载成功
    public static final    int LOAD_FAILURE = LOADING + 3;//加载失败
    public static final    int LOAD_NO_DATA = LOADING + 4;//无数据
    public static final  int LOAD_NO_WORK=LOADING+5;//不做加载刷新动画

    protected final static String TAG = "BaseActivity";

    private View fl_failure, fl_loading, fl_no_data;
    protected LayoutInflater mInflater;

    protected List autoCloseList = new ArrayList<>();

    Unbinder unbinder;
    private ACache         mACache;
    private RequestManager mGlide;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mInflater = getLayoutInflater();
        AppManager.getAppManager().addActivity(this);
        onBeforeSetContentLayout();
        Bundle extras = getIntent().getExtras();
        if (null != extras) {
            getBundleExtras(extras);
        }
        if (getContentViewId() != 0) {
            setContentView(getContentViewId());
        }
        if (getLoadFrameId() != 0) {
            bindLoadView((ViewGroup) findViewById(getLoadFrameId()));
        }


        // 通过注解绑定控件
        unbinder = ButterKnife.bind(this);

        init(savedInstanceState);
        initView();
        initData();
        requestData();
    }

    protected void requestData() {

    }

    protected int getLoadFrameId() {
        return 0;
    }

    protected void getBundleExtras(Bundle extras) {

    }

    public void autoClose(Object object) {
        autoCloseList.add(object);
    }

    /**
     * 所有网络请求 包括一般的json请求、文件上传下载使用Retrolfit
     *
     * @return requestApi
     */
    protected RequestApi getRequestApi() {
        return RequestHelper.getRequestApi();
    }

    /**
     * 媒体文件的下载、缓存、显示、本地加载使用Glide
     *
     * @return requestManager
     */
    public synchronized RequestManager getGlide() {
        if (mGlide == null) {
            mGlide = Glide.with(this);
        }
        return mGlide;
    }

    public synchronized ACache getACache() {
        if (mACache == null) {
            mACache = ACache.get(this);
        }
        return mACache;
    }

    protected int getContentViewId() {
        return 0;
    }

    protected void onBeforeSetContentLayout() {

    }

    protected void init(Bundle savedInstanceState) {

    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                onBackPressed();
                break;

            default:
                break;
        }
        return super.onOptionsItemSelected(item);
    }


    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        super.setContentView(layoutResID);
        adjustStatusBar();
    }

    @Override
    protected void onDestroy() {
        if (unbinder != null) {
            unbinder.unbind();
        }
        AppManager.getAppManager().finishActivity(this);
        if (autoCloseList != null) {
            for (Object object : autoCloseList) {
                if (object instanceof Call) {
                    ((Call) object).cancel();
                } else if (object instanceof Unbinder) {
                    ((Unbinder) object).unbind();
                }
            }
        }
        super.onDestroy();
    }

    void adjustStatusBar() {
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
            final View statusBar = findViewById(R.id.status_bar);
            if (statusBar != null) {
                statusBar.setVisibility(View.GONE);
            }
        }
    }

    /**
     * add fl_loading & error view
     */
    protected void bindLoadView(ViewGroup viewGroup) {
        if (fl_failure != null || fl_loading != null || viewGroup == null) {
            return;
        }
        fl_failure = mInflater.inflate(R.layout.static_network_error, viewGroup, false);
        viewGroup.addView(fl_failure, new ViewGroup.LayoutParams(-1, -1));
        fl_loading = mInflater.inflate(R.layout.static_loading, viewGroup, false);
        viewGroup.addView(fl_loading, new ViewGroup.LayoutParams(-1, -1));
        fl_no_data = mInflater.inflate(R.layout.static_no_data, viewGroup, false);
        viewGroup.addView(fl_no_data, new ViewGroup.LayoutParams(-1, -1));
        fl_failure.findViewById(R.id.reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestData();
            }
        });
        fl_failure.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        fl_loading.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });
        //        fl_no_data.setOnTouchListener(new View.OnTouchListener() {
        //            @Override
        //            public boolean onTouch(View v, MotionEvent event) {
        //                return true;
        //            }
        //        });
        LinearLayout layout = (LinearLayout) fl_no_data.findViewById(R.id.no_data_ll);
        layout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                requestData();
            }
        });
        //add listener
    }

    protected void updateLoadStatus(int status, String msg) {
        if (fl_failure == null || fl_loading == null) {
            return;
        }
        if (status == LOADING) {
            fl_loading.setVisibility(View.VISIBLE);
            fl_failure.setVisibility(View.GONE);
            fl_no_data.setVisibility(View.GONE);
        } else if (status == LOAD_FAILURE) {
            fl_loading.setVisibility(View.GONE);
            fl_failure.setVisibility(View.VISIBLE);
            fl_no_data.setVisibility(View.GONE);
        } else if (status == LOAD_SUCCESS || status == LOAD_NO_WORK) {
            fl_loading.setVisibility(View.GONE);
            fl_failure.setVisibility(View.GONE);
            fl_no_data.setVisibility(View.GONE);
        } else if (status == LOAD_ERROR) {
            fl_loading.setVisibility(View.GONE);
            fl_failure.setVisibility(View.GONE);
            if (StringUtils.isEmpty(msg)) {
                ((TextView) fl_no_data.findViewById(R.id.tv_tip)).setText(msg);
            }
            fl_no_data.setVisibility(View.VISIBLE);
        } else if (status == LOAD_NO_DATA) {
            fl_loading.setVisibility(View.GONE);
            fl_failure.setVisibility(View.GONE);
            fl_no_data.setVisibility(View.VISIBLE);
        }
    }

    protected void updateLoadStatus(int status) {
        updateLoadStatus(status, null);
    }


    public void initView() {
    }


    public void initData() {
    }


    public Context context() {
        return this;
    }


    public void back(View view) {
        onBackPressed();
    }


    public static final int SET_GONE = 0x01;
    public static final int SET_NULL = 0x02;
    public static final int SET_DEF  = 0x03;

    public void loadImg(ImageView imageView, String url, Integer id) {
        if (imageView == null) {
            return;
        }
        if (id != null) {
            Glide.with(this).load(url).apply(new RequestOptions().placeholder(id)).into(imageView);
        } else {
            Glide.with(this).load(url).apply(new RequestOptions().placeholder(Constants
                    .DEFAULT_LOADING_IMG)).into(imageView);
        }
    }

    public void loadNetImg(ImageView imageView, String url) {
        //华旗 等平台图片都没加ip地址
        loadImg(imageView,addHost(url),null);
//        loadImg(imageView, url, null);
    }

    public void loadImg(ImageView imageView, String url) {
        loadImg(imageView, url, null);
    }

    public void loadText(String label, TextView textView, String context, String def, View attach, int type) {
        if (Util.checkNull(textView)) {
            return;
        }
        if (attach != null) {
            attach.setVisibility(View.VISIBLE);
        }
        textView.setVisibility(View.VISIBLE);
        if (!Util.checkNull(context)) {
            textView.setText((label == null ? "" : label) + context);
        } else {
            switch (type) {
                case SET_GONE:
                    if (attach != null) {
                        attach.setVisibility(View.GONE);
                    }
                    textView.setVisibility(View.GONE);
                    break;
                case SET_NULL:
                    textView.setText(null);
                    break;
                case SET_DEF:
                    if (def != null) {
                        textView.setText((label == null ? "" : label) + def);
                    } else {
                        textView.setText((label == null ? "" : label) + "无数据");
                    }

                default:
                    break;
            }

        }
    }

    public void loadTextColon(TextView textView,String label,String def){
        if (textView ==null){
            return;
        }
        if (Util.checkNull(def)){
            textView.setText(label+": ");
        }else{
            textView.setText(label+": "+def);
        }
    }


    public void loadText(String label, TextView textView, String context, String def) {
        loadText(label, textView, context, def, null, SET_DEF);
    }

    public void loadText(String label, TextView textView, String context) {
        loadText(label, textView, context, null, null, SET_GONE);
    }

    public void loadText(TextView textView, String context) {
        loadText(null, textView, context, null, null, SET_GONE);
    }

    public void loadText(TextView textView, String context, String def) {
        loadText(null, textView, context, def, null, SET_DEF);
    }


    public String dateFormat(Long realStartDate) {
        return dateFormat(realStartDate, "yyyy年MM月dd日");
    }
    public String dateFormat1(Long realStartDate) {
        return dateFormat(realStartDate, "yyyy-MM-dd HH:mm:ss");
    }

    public String howLongTime(Long data1,Long data2) {
        long time = (data1 - data2) / 1000 / 60; //分钟
        if (time <= 1){
            return "1分钟";
        }else if (time < 60){
            //分钟
            return time+"分钟";
        }else if (time <= 60 * 24){
            return time/60+"小时";
        }else if (time <= 60 * 24 * 2){
            return time / (60 * 24) + "天";
        }
        return null;
    }

    public String dateFormat(Long realStartDate, String pattern) {
        if (Util.checkNull(realStartDate)) {
            return null;
        }
        return new SimpleDateFormat(pattern).format(new Date(realStartDate));
    }

    public static String[] addHost(String[] imgNames) {
        if (imgNames == null){
            return imgNames;
        }
        for (int i = 0; i < imgNames.length; i++) {
            if (!imgNames[i].contains("http")){
                imgNames[i] = Global.user.getServerAddress() + imgNames[i];
            }
        }
        return imgNames;
    }

    public static String addHost(String imgNames) {
        if (Util.checkNull(imgNames)){
            return imgNames;
        }
        if (!imgNames.contains("http")){
            return Global.user.getServerAddress() + imgNames;
        }
        return imgNames;
    }

    /**
     * 点击EditText文本框之外任何地方隐藏键盘的解决办法
     *
     * @param ev
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            View v = getCurrentFocus();
            if (isShouldHideInput(v, ev)) {

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                if (imm != null) {
                    imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
                }
            }
            return super.dispatchTouchEvent(ev);
        }
        // 必不可少，否则所有的组件都不会有TouchEvent了
        if (getWindow().superDispatchTouchEvent(ev)) {
            return true;
        }
        return onTouchEvent(ev);
    }

    public boolean isShouldHideInput(View v, MotionEvent event) {
        if (v != null && (v instanceof EditText)) {
            int[] leftTop = {0, 0};
            //获取输入框当前的location位置
            v.getLocationInWindow(leftTop);
            int left = leftTop[0];
            int top = leftTop[1];
            int bottom = top + v.getHeight();
            int right = left + v.getWidth();
            return !(event.getX() > left && event.getX() < right
                    && event.getY() > top && event.getY() < bottom);
        }
        return false;
    }
}
